package com.marketsim.main;

import com.marketsim.analysis.PortfolioUtils;
import com.marketsim.analysis.StatisticCalculatorJ8;
import com.marketsim.dao.StockTickerDAO;
import com.marketsim.simulator.PricesHistoricalData;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Alex on 06.04.2014.
 */
public class Lab1MainApp {

    public static void main(String[] arg) {
        Lab1MainApp mainAppLab1 = new Lab1MainApp();
        mainAppLab1.lab1();
    }

    private void lab1() {

        String[] tickers = {"AAPL", "GOOGL", "IBM", "MSFT"};

        DateFormat dateFormat = new SimpleDateFormat("d-M-yyyy", Locale.ENGLISH);
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = dateFormat.parse("1-1-2010");
            endDate = dateFormat.parse("31-12-2010");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        StockTickerDAO tickerDAO = StockTickerDAO.getInstance();
        PricesHistoricalData pricesHistoricalData = tickerDAO.getStockInfo(Arrays.asList(tickers), startDate, endDate);

        List<List<BigDecimal>> historicalReturns
                = pricesHistoricalData.getReturns();
        BigDecimal maxSharpRatio = BigDecimal.ZERO;
        Double[] bestAllocation = null;
        for (int w1 = 0; w1 <= 10; w1++) {
            for (int w2 = 0; w2 <= 10; w2++) {
                for (int w3 = 0; w3 <= 10; w3++) {
                    for (int w4 = 0; w4 <= 10; w4++) {
                        if (w1 + w2 + w3 + w4 == 10) {
                            Double[] allocation = {w1 / 10d, w2 / 10d, w3 / 10d, w4 / 10d};
                            List<BigDecimal> portfolioReturns =
                                    PortfolioUtils.getReturnOfPortfolio(historicalReturns, Arrays.asList(allocation));
                            BigDecimal currentSharpRatio = StatisticCalculatorJ8.getSharpRatio(portfolioReturns);
                            if (currentSharpRatio.compareTo(maxSharpRatio) > 0) {
                                maxSharpRatio = currentSharpRatio;
                                bestAllocation = allocation;
                            }
                        }
                    }
                }
            }
        }

        System.out.println("Max sharp ratio is " + maxSharpRatio);
        System.out.println("Best portfolio allocation is " + bestAllocation[0] + " " + bestAllocation[1] + " "
                + bestAllocation[2] + " " + bestAllocation[3]);
    }

}
